package com.bbcare.followup.plat.task;

import java.net.InetAddress;
import java.net.UnknownHostException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.commons.collections.MapUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;

import com.bbcare.comm.AppException;
import com.bbcare.comm.Constants;
import com.bbcare.comm.DateUtil;
import com.bbcare.comm.ErrorCode;
import com.bbcare.comm.SeqUtil;
import com.bbcare.comm.ToolUtils;
import com.bbcare.followup.plat.entity.FuInformruleDict;
import com.bbcare.followup.plat.entity.PtSmsRd;
import com.bbcare.followup.plat.entity.Tguidance;
import com.bbcare.followup.plat.store.ibatis.IConfCacheDAO;
import com.bbcare.followup.plat.store.ibatis.IPatientDAO;
import com.bbcare.followup.plat.store.ibatis.IPtSmsRdDao;
import com.bbcare.followup.plat.store.ibatis.ISmsTemplateDAO;
/**
 * 国妇婴诊后指导定时发送短信
 * @author
 *
 */
public class PtPatientSendTask{

	private final Log logger = LogFactory.getLog(PtPatientSendTask.class);

	@Autowired
    private IPatientDAO patientDao;

	@Autowired
    private IConfCacheDAO confCacheDao;

	@Autowired
    private ISmsTemplateDAO smsTemplDao;

	@Autowired
	private IPtSmsRdDao IPtSmsRdDao;

	public void executeTask() {
		logger.info("......PtPatientSendTask start.....");
		Map<String, Object> inRule = new HashMap<String, Object>();
        inRule.put("status", Constants.TABLE_RECORD_STATUS_NOMAL);
        inRule.put("queueStatus", Constants.QUEUE_STATUS_NOMAL);
        inRule.put("ruleType", Constants.FU_INFORM_RULE_SMS_TG_SEND_RULE_TYPE_DOCTOR);// 国妇婴诊疗指导短信
        List<Map<String, Object>> outRuleList = null;
        try {
            outRuleList = confCacheDao.listWinQueueFromInformRule(inRule);
            if(!CollectionUtils.isEmpty(outRuleList)){
            	// 查询短信提醒规则配置
                Map<String, Object> ruleMapIn = new HashMap<String, Object>();
                ruleMapIn.put("queueId", outRuleList.get(0).get("queueId"));
                ruleMapIn.put("fuInformid", outRuleList.get(0).get("id"));
                List<FuInformruleDict> informRuleList = confCacheDao.getRuleByQueueId(ruleMapIn);
                if (CollectionUtils.isEmpty(informRuleList)) {
                    throw (new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_TASK_INFORMRULE_NOT_EXIST,"该队列未配置随访提醒规则或开关未放开，请联系系统管理员！"));
                }
                FuInformruleDict fifdVo = informRuleList.get(0);
                Map<String, Object> smsTemplMapIn = new HashMap<String, Object>();
                Map<String, Object> smsTemplMapOut = new HashMap<String, Object>();

                smsTemplMapIn.clear();
                smsTemplMapOut.clear();
                smsTemplMapIn.put("id", fifdVo.getSmsTemplid());
                smsTemplMapIn.put("status", Constants.TABLE_RECORD_STATUS_NOMAL);
                smsTemplMapOut = smsTemplDao.selectSmsTemplateById(smsTemplMapIn);
                if (MapUtils.isEmpty(smsTemplMapOut)) {
                    throw (new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_SMS_TEMPL_NOT_EXIST,"对应短信模板未配置或开关未放开，请联系系统管理员！"));
                }
                // 替换短信模板中的变量
                //尊敬的家长您好，您今日宝宝的儿保门诊，指导意见已出，点击下载APP后可进行查看：http://t.cn/R5z2N5t ,您的登录帐号为：${phone}，默认密码为：手机号后六位。
                String createDate = DateUtil.getCurrDate2();//获取当天日期yyyy-MM-dd
        		//通过日期查询要发送短信的数据
        		List<Tguidance> list = patientDao.listtGuidances(createDate);
        		if(!CollectionUtils.isEmpty(list)){
        			for (int i = 0; i < list.size(); i++) {
        				//改变状态发送短信(乐观锁)
        				int num = patientDao.updatetGuidance(list.get(i).getId());
        				if(num>0 && !StringUtils.isEmpty(list.get(i).getPhoneNo())){
        					//替换
        					String informTypeBuffer = (String)smsTemplMapOut.get("sign")+smsTemplMapOut.get("smsTemplate");
        					informTypeBuffer = informTypeBuffer.replace("${phone}", list.get(i).getPhoneNo());
        					logger.info("短信发送内容:"+informTypeBuffer);
        					//发送短信
        					int stage = ToolUtils.sendYMsms3(list.get(i).getPhoneNo().trim(), informTypeBuffer.toString());
        					String sendSatus = "0";
        					if(stage==0){
        						sendSatus = "1";
        					}
        					logger.info("电话:"+list.get(i).getPhoneNo().trim()+",短信发送状态:"+stage);
        					String updateTime = DateUtil.getTimeString(DateUtil.getSysDateA());// 当前时间
        					String ptSmsId = SeqUtil.getSeqNo(Constants.SEQ_NO_FOR_PT_SMS_RD_ID);
        					String updateAccept = SeqUtil.getSeqNo(Constants.SEQ_NO_FOR_SYSTEMID);// 操作流水
        					// 发送主机ip
        					String ipAddress = "";
        					try {
        						InetAddress netAddress = InetAddress.getLocalHost();
        						ipAddress = netAddress.getHostAddress();
        					} catch (UnknownHostException e) {
        						e.printStackTrace();
        						ipAddress = "";
        					}
        					PtSmsRd psrVo = new PtSmsRd();
        					psrVo.setCheckStatus("01");
        					psrVo.setCreateTime(updateTime);
        					psrVo.setId(ptSmsId);
        					psrVo.setPhoneNo(list.get(i).getPhoneNo());
        					psrVo.setPtSchemeid(fifdVo.getId());
        					psrVo.setQueueId(fifdVo.getQueueId());
        					psrVo.setSendIp(ipAddress);
        					psrVo.setSmsText(informTypeBuffer);
        					psrVo.setSmsType("05");
        					psrVo.setUpdateAccept(updateAccept);
        					psrVo.setUserId(list.get(i).getUserId());
        					psrVo.setVerifyStatus("00");
        					psrVo.setInformType(Constants.FU_INFORM_RULE_SMS_TG_SEND_RULE_TYPE_DOCTOR);
        					psrVo.setSendStatus(sendSatus);
        					psrVo.setInformType(Constants.FU_INFORM_RULE_TYPE_SMS);
        					IPtSmsRdDao.savePtSmsRd(psrVo);
        				}
					}
        		}
            }
        } catch (Exception e1) {
            e1.printStackTrace();
            return;
        }
        logger.info("......PtPatientSendTask end.....");
	}
}
